const { default: inquirer } = require("inquirer");
const chalk = require("chalk");
const pkgEdit = require("edit-json-file");
const { frameworks, frameworkGitUrl } = require("../../config.js");
const download = require("./download");
const createApp = async (projectName) => {
  const answers = await inquirer.prompt([
    {
      type: "input",
      name: "projectName",
      message: "请输入项目名称",
      default: projectName,
    },
    {
      type: "list",
      name: "framework",
      message: "请选择您要使用的项目模版",
      choices: frameworks,
      default: "express",
    },
    // {
    //   type: "confirm",
    //   name: "install",
    //   message: "是否安装依赖？",
    //   default: true,
    // },
  ]);
  const { projectName: name, framework } = answers;
  const gitUrl = frameworkGitUrl[framework];
  try {
    await download(gitUrl, name);
    try {
      await pkgEdit(`${name}/package.json`, {
        async: true,
      })
        .set("name", name)
        .set("description", `This is a ${framework} project`)
        .save();
    } catch (err) {
      console.log(
        chalk.red("----------package.json文件修改失败！----------", err)
      );
    }
    console.log(chalk.green("----------项目创建成功！----------"));
    console.log(chalk.green("----------请进入项目目录,并安装依赖----------"));
    console.log("cd " + name);
    console.log("npm install");
    console.log("npm run dev");
  } catch {
    console.log(chalk.red("----------项目创建失败！----------"));
  }
};

module.exports.createApp = createApp;
